package com.ddw.wotcg.server.utils;

import java.io.IOException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public abstract class TemplateHelper {
	
	public static final String SESSION_COOKIE = "session";
	
	public static void appendPageData(Map<String, Object> parent, String title) {
		final Map<String, Object> data = new HashMap<String, Object>();
		data.put("title", title);
		parent.put("page", data);
	}
	
	public static void appendUserData(Map<String, Object> root, User user) {
		final Map<String, Object> data = new HashMap<String, Object>();
		data.put("active", false);
		
		// Check if session exists
		if (user != null) {
			data.put("active", true);
			data.put("email", user.email);
			data.put("username", user.username);
			data.put("created", user.created);
		}
		
		root.put("session", data);
	}
	
	public static void callTemplate(Configuration config,
			HttpServletResponse response, String template,
			Map<String, Object> root) throws IOException, ServletException {
		final Template t = config.getTemplate(template);
		response.setContentType("text/html; charset=utf-8");
		final Writer out = response.getWriter();
		try {
			t.process(root, out);
		} catch (final TemplateException e) {
			throw new ServletException("Failed to process FreeMarker template",
					e);
		}
	}
}
